<template>
  <div class="ms-list">
    <el-row class="operation">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">
          <icon style="color: #0088cc" name="home"></icon>
        </el-breadcrumb-item>
        <el-breadcrumb-item>系统设置</el-breadcrumb-item>
        <el-breadcrumb-item>组织架构</el-breadcrumb-item>
        <el-breadcrumb-item>系统角色</el-breadcrumb-item>
        <el-breadcrumb-item>列表</el-breadcrumb-item>
      </el-breadcrumb>
      <el-button-group>
        <el-button type="primary" size="small" @click="addRow()">新增</el-button>
      </el-button-group>
    </el-row>

    <ms-slide
      :title="row.edit.enabled ? '编辑角色' : '新增角色'"
      :width="500"
      @close="closeSlide()"
      ref="slideModifyRow">
      <el-form class="form" label-width="120px" size="small" :model="row.form" ref="formModifyRow">
        <el-form-item label="所属部门" prop="departmentId" :rules="[{required: true, message: '必填'}]">
          <el-select v-model="row.form.departmentId">
            <template v-for="department in departments">
              <el-option :label="department.title" :value="department.id"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="角色名称" prop="title" :rules="[{required: true, message: '必填'}]">
          <el-input v-model="row.form.title"></el-input>
        </el-form-item>
        <el-form-item label="角色数据范围" prop="dataScope" :rules="[{required: true, message: '必填'}]">
          <el-select v-model="row.form.dataScope">
            <el-option label="无数据权限" :value="0"></el-option>
            <el-option label="仅本人" :value="1"></el-option>
            <el-option label="本人及当前部门" :value="2"></el-option>
            <el-option label="本部门所有" :value="3"></el-option>
            <el-option label="全部" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitRow()">提交</el-button>
          <el-button v-if="!row.edit.enabled" @click="resetForm('formModifyRow')">重置</el-button>
        </el-form-item>
      </el-form>
    </ms-slide>

    <el-table v-loading="table.loading" size="small" stripe border :data="table.list" :fit="true">
      <el-table-column prop="id" label="ID" min-width="80" fixed></el-table-column>
      <el-table-column prop="departmentTitle" label="所属部门" min-width="80" fixed></el-table-column>
      <el-table-column prop="title" label="角色名称" min-width="200">
        <template slot-scope="scope">
          <span>{{scope.row.title}}</span>
          <span v-if="scope.row.dataScope === 0">[无数据权限]</span>
          <span v-if="scope.row.dataScope === 1">[仅本人]</span>
          <span v-if="scope.row.dataScope === 2">[本人及当前部门]</span>
          <span v-if="scope.row.dataScope === 3">[本部门所有]</span>
          <span v-if="scope.row.dataScope === 4">[全部]</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="100" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click.native.prevent="editRow(scope.$index)">编辑</el-button>
          <el-button type="text" size="small" @click.native.prevent="deleteRow(scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="pagination"
      layout="total, sizes, prev, pager, next, jumper"
      :current-page.sync="table.pagination.page"
      :total="table.pagination.totalRow"
      :page-size="table.pagination.pageSize"
      :page-sizes="table.pagination.pageSizes"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"/>

  </div>
</template>

<script>
  import MsSlide from '@/components/common/Slide.vue'
  import Api from '@/api/customer/system/system-role'
  import DepartmentApi from '@/api/customer/system/system-department'
  import FormTokenApi from '@/api/system/form-token'
  import ResponseParse from '@/utils/response-parse'
  export default {
    components: {
      MsSlide
    },
    data () {
      return {
        table: {
          loading: true,
          list: [],
          pagination: {}
        },
        row: {
          form: {},
          edit: {
            index: 0,
            enabled: false
          }
        },
        departments: []
      }
    },
    created () {
      this.table.list = []
      this.requestList()

      DepartmentApi.listChild({pid: 0}, response => {
        let status = response.status || 0
        let body = response.data || []
        if (status >= 200 && status <= 204) {
          this.departments = body
        }
      })
    },
    methods: {
      requestList () {
        this.table.loading = true

        const search = Object.assign({}, this.table.pagination)
        Api.list({search: search}, response => {
          let status = response.status || 0
          let body = response.data || []
          if (status >= 200 && status <= 204) {
            this.table.list = body
            this.table.pagination = ResponseParse.pagination(response.headers)
//            if (this.table.pagination.totalPage === this.table.pagination.page) {
//              this.tbHeight = ''
//            } else {
//              this.$set(this, 'tbHeight', this.PHeigh - this.$refs.msSearch.clientHeight)
//            }
          } else {
//            this.tbHeight = ''
            this.table.list = []
            this.$message.error(body.error || '数据获取失败')
          }
          this.table.loading = false
        })
      },
      addRow () {
        this.row.edit.enabled = false
        this.row.edit.index = 0
        this.row.form = {}

        // 获得 form token
        FormTokenApi.create(response => {
          let status = response.status || 0
          let body = response.data || []
          if (status >= 200 && status <= 204) {
            this.row.form.token = body.token || ''
          }
        })

        this.showSlide('slideModifyRow')
      },
      editRow (index) {
        this.row.form = Object.assign({}, this.table.list[index])
        this.row.edit.enabled = true
        this.row.edit.index = index

        this.showSlide('slideModifyRow')
      },
      deleteRow (index) {
        Api.delete({id: this.table.list[index].id}, response => {
          let status = response.status || 0
          let body = response.data || []
          if (status >= 200 && status <= 204) {
            this.table.list.splice(index, 1)
            this.$message.success('删除成功')
          } else {
            this.$message.error(body.error || '删除失败')
          }
        })
      },
      submitRow () {
        this.$refs['formModifyRow'].validate((valid) => {
          if (valid) {
            if (this.row.edit.enabled) {
              Api.modify({id: this.row.form.id, form: this.row.form}, response => {
                let status = response.status || 0
                let body = response.data || {}
                if (status >= 200 && status <= 204) {
                  let index = this.row.edit.index
                  let data = Object.assign({}, this.table.list[index], body)
                  this.table.list.splice(index, 1, data)
                  this.$message.success('修改成功')

                  // 关闭
                  this.$refs['slideModifyRow'].close()
                } else {
                  this.$message.error(body.error || '修改失败')
                }
              })
            } else {
              Api.create({form: this.row.form}, response => {
                let status = response.status || 0
                let body = response.data || {}
                if (status >= 200 && status <= 204) {
                  // 新数据加到数组开头
                  this.table.list.unshift(body)
                  this.$message.success('新增成功')

                  // 关闭
                  this.$refs['slideModifyRow'].close()
                } else {
                  this.$message.error(body.error || '新增失败')
                }
              })
            }
          } else {
            return false
          }
        })
      },
      handleSizeChange (val) {
        this.table.pagination.pageSize = val
        this.requestList()
      },
      handleCurrentChange (val) {
        this.table.pagination.page = val
        this.requestList()
      },
      showSlide (ref) {
        this.$refs[ref].show()
      },
      closeSlide () {
        this.row.form = {}
        this.row.edit.index = 0
      },
      resetForm (formName) {
        this.$refs[formName].resetFields()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .ms-list {
    .control-label {
      padding-right: 3px;
      font-weight: bold;
      .ms-stress {
        padding: 0 3px 0 13px;
        color: #f00;
      }
    }
    .permission-list {
      padding-left: 10px;
      list-style: none;
      .permission-title, .submenu-title {
        display: block;
      }
      .permission-title:hover, .submenu-title:hover {
        background-color: #eef1f6;
      }
      .permission-title {
        font-weight: bold;
        line-height: 25px;
        background-color: #fafafa;
        margin-bottom: 5px;
      }
      .permission-title-bg {
        background-color: #eef1f6;
      }
      .submenu-box {
        display: inline-block;
        padding-left: 10px;
        font-size: 12px;
      }
    }
    .permission-button {
      padding-left: 10px;
    }
  }
</style>

<style lang="scss">
  .submenu-box {
    .el-checkbox {
      font-size: 12px;
      .el-checkbox__label {
        font-size: 12px;
      }
      .el-checkbox__inner {
        width: 12px;
        height: 12px;
      }
      .el-checkbox__inner {
        position: static;
      }
    }
  }
</style>
